package com.googlecode.mgwt.examples.uibinder.client.activities;

import java.util.ArrayList;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.googlecode.mgwt.examples.uibinder.client.ClientFactory;
import com.googlecode.mgwt.examples.uibinder.client.Topic;
import com.googlecode.mgwt.examples.uibinder.client.places.ExamplePlace;
import com.googlecode.mgwt.examples.uibinder.client.places.ExamplePlace.ID;
import com.googlecode.mgwt.mvp.client.MGWTAbstractActivity;

public class ExampleListActivity extends MGWTAbstractActivity implements ExampleListDisplay.Presenter {

	private final ClientFactory clientFactory;
	private ExampleListDisplay display;
	private ArrayList<Topic> list;
	private int lastIndex = -1;

	public ExampleListActivity(ClientFactory clientFactory) {
		this.clientFactory = clientFactory;

	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		display = clientFactory.getExampleListDisplay();
		display.setPresenter(this);

		ID[] values = ID.values();

		list = new ArrayList<Topic>(values.length);

		for (int i = 1; i < values.length; i++) {
			list.add(new Topic(values[i].getName()));
		}
		lastIndex = -1;
		display.render(list);
		panel.setWidget(display);
	}

	@Override
	public void onStop() {
		display.setPresenter(null);
	}

	@Override
	public void onItemSelected(int index) {

		if (lastIndex != -1) {
			display.setSelected(lastIndex, false);
		}
		ID id = ID.values()[index + 1];
		lastIndex = index;
		display.setSelected(index, true);
		clientFactory.getPlaceController().goTo(new ExamplePlace(id));
	}

}
